//
//  SYStatusListViewModel.swift
//  YANAWeibo
//
//  Created by mac on 16/5/15.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//  tableview对应的viewmodel
class SYStatusListViewModel: NSObject {
    // 保存微博数据
    var statusList: [SYStatusViewModel]?
    
    // 获取微博数据
    func requestStatus(isPullUp: Bool, complete: (isSuccess: Bool, message: String)->()) {
        
        // 上啦加载使用的默认maxid
        var maxId: Int64 = 0
        // 下拉刷新使用的
        var sinceId: Int64 = 0
        
        if isPullUp {
            maxId = statusList?.last?.status?.id ?? 0
            // 取出重复
            if maxId > 0 {
                maxId -= 1
            }
        } else {
            sinceId = statusList?.first?.status?.id ?? 0
        }
        
        SYNetWorkTools.sharedTools.requestStatus(SYUserAccountViewModel.sharedUserAccount.accessToken!, maxId: maxId, sinceId: sinceId) { (response, error) -> () in
            
            var resultMessage: String = "没有加载到微博数据"
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false, message: resultMessage)
                return
            }
            
            guard let dic = response as? [String: AnyObject] else {
                print("不是一个正确的json格式")
                complete(isSuccess: false, message: resultMessage)
                return
            }
            
            guard let statusArray = dic["statuses"] as? [[String: AnyObject]] else {
                print("不是一个正确的json格式")
                complete(isSuccess: false, message: resultMessage)
                return
            }
            //遍历数组字典初始化模型
            var tempArray = [SYStatusViewModel]()
            for value in statusArray {
                let status = SYStatus(dic: value)
                let statusViewModel = SYStatusViewModel(status: status)
                tempArray.append(statusViewModel)
            }
            
            if self.statusList == nil {
                self.statusList = [SYStatusViewModel]()
            }
            
            if isPullUp {
                //上啦追加数据
                self.statusList = self.statusList! + tempArray
            } else {
                self.statusList = tempArray + self.statusList!
            }
            
            let count = tempArray.count
            
            if count > 0 {
                resultMessage = "加载了\(count)条微博数据"
            } else if count == 0 {
                resultMessage = "没有新的微博可以加载"
            }
                
            complete(isSuccess: true, message: resultMessage)
            
            
        }
    }

}
